<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="供应商ID" prop="supplierId">
        <el-input v-model="queryParams.supplierId" placeholder="请输入供应商ID" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="供应商名称" prop="supplierName">
        <el-select v-model="queryParams.supplierName" placeholder="请选择供应商名称">
          <el-option v-for="dict in supplier_type" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="货物ID" prop="productId">
        <el-input v-model="queryParams.productId" placeholder="请输入货物ID" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['jinhuoguanli:purchase:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['jinhuoguanli:purchase:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['jinhuoguanli:purchase:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['jinhuoguanli:purchase:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="进货ID" align="center" prop="id" />
      <!-- <el-table-column label="供应商名称" align="center" prop="sysSupplier.supplierName" /> -->
      <!-- 添加供应商相关列 -->
      <el-table-column label="供应商名称" align="center" prop="sysSupplier.supplierName">
        <template #default="scope">
          <dict-tag :options="supplier_type" :value="scope.row.sysSupplier.supplierName" />
        </template>
      </el-table-column>
      <el-table-column label="货物名称" align="center" prop="sysProduct.productName" />
      <el-table-column label="支付类型" align="center" prop="paymentType" />
      <el-table-column label="进货时间" align="center" prop="purchaseTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.purchaseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作员" align="center" prop="operator" />
      <el-table-column label="进货数量" align="center" prop="purchaseQuantity" />
      <el-table-column label="进货价格" align="center" prop="purchasePrice" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['jinhuoguanli:purchase:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['jinhuoguanli:purchase:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改商品进货对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="purchaseRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="供应商名称" prop="sysSupplier.supplierName">
          <el-input v-model="form.sysSupplier.supplierName" placeholder="请输入供应商名称" />
        </el-form-item> -->
        <el-form-item label="供应商名称" prop="sysSupplier.supplierName">
          <el-select v-model="form.sysSupplier.supplierName" placeholder="请选择供应商名称">
            <el-option v-for="dict in supplier_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="商品名称" prop="sysProduct.productName">
          <el-input v-model="form.productId" placeholder="请输入商品名称" />
        </el-form-item> -->
        <el-form-item label="支付类型" prop="paymentType">
          <el-input v-model="form.paymentType" placeholder="请输入支付类型" />
        </el-form-item>
        <el-form-item label="进货时间" prop="purchaseTime">
          <el-date-picker clearable v-model="form.purchaseTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择进货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="操作员" prop="operator">
          <el-input v-model="form.operator" placeholder="请输入操作员" />
        </el-form-item>
        <el-form-item label="进货数量" prop="purchaseQuantity">
          <el-input v-model="form.purchaseQuantity" placeholder="请输入进货数量" />
        </el-form-item>
        <el-form-item label="进货价格" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" placeholder="请输入进货价格" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Purchase">
import { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase } from "@/api/jinhuoguanli/purchase"
import { getSupplierBySupplierName } from "../../../api/jichuguanli/supplier"

const { proxy } = getCurrentInstance()
const { supplier_type } = proxy.useDict('supplier_type')
const purchaseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierId: null,
    productId: null,
    supplierName: null,
    productName: null
  },
  rules: {
    // 嵌套属性验证 - 正确写法
    'sysSupplier.supplierName': [
      { required: true, message: '请选择供应商名称', trigger: 'change' }
    ],
    supplierId: [
      { required: true, message: "供应商ID不能为空", trigger: "blur" }
    ],
    productId: [
      { required: true, message: "商品ID不能为空", trigger: "blur" }
    ],
    paymentType: [
      { required: true, message: "支付类型不能为空", trigger: "change" }
    ],
    purchaseTime: [
      { required: true, message: "进货时间不能为空", trigger: "blur" }
    ],
    operator: [
      { required: true, message: "操作员不能为空", trigger: "blur" }
    ],
    purchaseQuantity: [
      { required: true, message: "进货数量不能为空", trigger: "blur" }
    ],
    purchasePrice: [
      { required: true, message: "进货价格不能为空", trigger: "blur" }
    ],
    totalAmount: [
      { required: true, message: "总金额不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询商品进货列表 */
function getList() {
  loading.value = true
  listPurchase(queryParams.value).then(response => {
    purchaseList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    supplierId: null,
    productId: null,
    paymentType: null,
    purchaseTime: null,
    operator: null,
    purchaseQuantity: null,
    purchasePrice: null,
    totalAmount: null,
    remark: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    sysSupplier: {},
    sysProduct: {}
  }
  // 重置查询参数
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,  // 假设默认页大小为10，根据你的实际需求调整
    supplierName: null,
    supplierId: null
    // 其他可能的查询参数也需要在这里重置
  }
  proxy.resetForm("purchaseRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  const sid = null
  const _name = queryParams.value.supplierName
  // 穿的是supplierName需要转成
  if (_name != null) {
    getSupplierBySupplierName(_name).then(response => {
      queryParams.value.supplierId = response.data.id;
      getList()
    })
  } else {
    getList()
  }
  // console.log(queryParams);
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  reset()
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品进货"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPurchase(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商品进货"
  })
}

/** 提交按钮 */
function submitForm() {
  // proxy.$refs["purchaseRef"].validate(valid => {
  //   if (valid) {
  //     if (form.value.id != null) {
  //       updatePurchase(form.value).then(response => {
  //         proxy.$modal.msgSuccess("修改成功")
  //         open.value = false
  //         getList()
  //       })
  //     } else {
  //       addPurchase(form.value).then(response => {
  //         proxy.$modal.msgSuccess("新增成功")
  //         open.value = false
  //         getList()
  //       })
  //     }
  //   }
  // })
  const _name = form.value.sysSupplier.supplierName;
  console.log(form.value.id);

  proxy.$refs["purchaseRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        // 先获取供应商ID
        getSupplierBySupplierName(_name).then(response => {
          form.value.supplierId = response.data.id;
          // 获取ID后再更新产品
          return updatePurchase(form.value);
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error("更新失败:", error);
        });
      } else {
        // 先获取供应商ID
        getSupplierBySupplierName(_name).then(response => {
          form.value.supplierId = response.data.id;
          // 获取ID后再更新产品
          return addPurchase(form.value);
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error("新增失败:", error);
        });
        // addPurchase(form.value).then(response => {
        //   proxy.$modal.msgSuccess("新增成功")
        //   open.value = false
        //   getList()
        // })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商品进货编号为"' + _ids + '"的数据项？').then(function () {
    return delPurchase(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('jinhuoguanli/purchase/export', {
    ...queryParams.value
  }, `purchase_${new Date().getTime()}.xlsx`)
}

getList()
</script>
